package cn.cttic.common.satoken.utils;

import cn.cttic.common.core.enums.DeviceType;
import cn.cttic.common.satoken.model.AppLoginUser;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaStorage;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.hutool.core.util.ObjectUtil;

public class AppLoginHelper {

    public static final String LOGIN_USER_KEY = "appLoginUser";
    public static final String USER_KEY = "appUserId";

    /**
     * 登录系统 基于 设备类型
     * 针对相同用户体系不同设备
     *
     * @param loginUser 登录用户信息
     */
    public static void loginByDevice(AppLoginUser loginUser, DeviceType deviceType) {
        SaStorage storage = SaHolder.getStorage();
        storage.set(LOGIN_USER_KEY, loginUser);
        storage.set(USER_KEY, loginUser.getUserId());
        SaLoginModel model = new SaLoginModel();
        if (ObjectUtil.isNotNull(deviceType)) {
            model.setDevice(deviceType.getDevice());
        }
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
//        UserType userType = UserType.getUserType(loginUser.getUserType());
//        if (userType == UserType.SYS_USER) {
//            model.setTimeout(86400).setActiveTimeout(1800);
//        } else if (userType == UserType.APP_USER) {
//            model.setTimeout(86400).setActiveTimeout(1800);
//        }
        StpUserUtil.login(loginUser.getLoginId(), model.setExtra(USER_KEY, loginUser.getUserId()));
        StpUserUtil.getTokenSession().set(LOGIN_USER_KEY, loginUser);
    }

    public static void refreshLoginUserInfo(AppLoginUser loginUser, DeviceType deviceType) {
        SaStorage storage = SaHolder.getStorage();
        storage.set(LOGIN_USER_KEY, loginUser);
        storage.set(USER_KEY, loginUser.getUserId());
        SaLoginModel model = new SaLoginModel();
        if (ObjectUtil.isNotNull(deviceType)) {
            model.setDevice(deviceType.getDevice());
        }
    }

    /**
     * 登录系统 基于 设备类型
     * 针对相同用户体系不同设备
     *
     * @param loginUser 登录用户信息
     */
    public static void refreshLoginUser(AppLoginUser loginUser) {
        SaStorage storage = SaHolder.getStorage();
        storage.set(LOGIN_USER_KEY, loginUser);
        storage.set(USER_KEY, loginUser.getUserId());
    }

    /**
     * 获取用户(多级缓存)
     */
    public static AppLoginUser getAppLoginUser() {
        try {
            AppLoginUser loginUser = (AppLoginUser) SaHolder.getStorage().get(LOGIN_USER_KEY);
            if (loginUser != null) {
                return loginUser;
            }
            SaSession session = StpUserUtil.getTokenSession();
            if (ObjectUtil.isNull(session)) {
                return null;
            }
            loginUser = (AppLoginUser) session.get(LOGIN_USER_KEY);
            SaHolder.getStorage().set(LOGIN_USER_KEY, loginUser);
            return loginUser;
        } catch (Exception ex) {
            return null;
        }
    }
}
